<template>
  <div class="">
    <el-card class="box-card">
      <el-button type="primary" @click="addTrademark" icon="Plus">添加品牌</el-button>
      <el-table :data="trademarkArr" border style="margin: 10px 0;">
        <el-table-column type="index" label="序号" width="100px" align="center"/>
        <el-table-column prop="tmName" label="品牌名称" align="center"/>
        <!-- <el-table-column label="品牌名称" align="center">
          <template #="{row}">
            <pre>{{row.tmName}}</pre>
          </template>
        </el-table-column> -->
        <el-table-column label="品牌LOGO" align="center">
          <template #="{row}">
            <img :src="row.logoUrl" alt="" style="width: 50px;height: 50px;">
          </template>
        </el-table-column>
        <el-table-column prop="address" label="品牌操作" align="center">
          <template #="{row}">
            <el-button type="primary" size="small" icon="Edit" @click="updateTrademark(row)"></el-button>
            <el-popconfirm :title="`确定删除${row.tmName}吗？`" width="220px" icon="Delete" @confirm="removeTradeMark(row.id)">
              <template #reference>
                <el-button type="danger" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 
        v-model:current-page 分页器当前显示页码
        v-model:page-size 每页展示数据条数
        :background 分页器按钮背景颜色
        layout 设置分页器6个子组件布局的调整
       -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[5, 10, 15, 20, 25]"
        :background="true"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
        @current-change="getHasTrademark"
        @size-change="sizeChange"
      />
    </el-card>
    <!-- 新增品牌对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id?'修改品牌':'添加品牌'">
      <el-form :model="trademarkParams" :rules="rules" ref="formRef" label-width="120px" style="width: 80%;">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input placeholder="请输入品牌名称" v-model="trademarkParams.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- action:图片上传路径，要书写/api，否则代理服务器不发送这次post请求 -->
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 #footer -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// 引入组合式API函数 ref
import { ref,onMounted,reactive,nextTick } from 'vue'
import { reqHasTrademark,reqAddOrUpdateTrademark,reqDeleteTrademark } from '@/api/product/trademark';
// @ts-ignore
import type {Records,TradeMarkResponseData,TradeMark} from './type'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
// 当前页码
let pageNo = ref<number>(1)
// 每页展示数据条数
let limit = ref<number>(5)
// 存储已有品牌数据的总数
let total = ref<number>(0)
// 存储已有品牌的数据
let trademarkArr = ref<Records>([])
let formRef = ref()
// 对话框显隐
let dialogFormVisible = ref<boolean>(false)
// 定义对象使用reactive代理方法，获取代理对象，类型约束为TradeMark
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})
// 获取已有品牌的接口 封装为一个函数
const getHasTrademark = async (pager=1)=> {
  pageNo.value = pager
  let result:TradeMarkResponseData = await reqHasTrademark(pageNo.value,limit.value)
  // console.log(result.data)
  if(result.code == 200){
    total.value = result.data.total
    trademarkArr.value = result.data.records
  }
}
// 组件挂载完毕钩子
onMounted(() => {
  getHasTrademark()
})
// 分页器当前页码发生变化时，再次发请求获取数据
// const changePageNo = ()=> {
//   getHasTrademark()
// }

// page-size 改变时触发
const sizeChange = ()=> {
  // pageNo.value = 1 //当前每一页数据量发生变化，页码归1
  getHasTrademark()
}
// 添加品牌
const addTrademark = ()=> {
  // 收集数据清空
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  dialogFormVisible.value = true
  // 初次点击新增对话框，表单项还没有渲染，formRef.value值为undefined
  //第一种写法： ts问号语法 formRef.value?表示：form组件有了才会调用resetFields()方法，没有就不会调用
  // formRef.value?.clearValidate('tmName')
  // formRef.value?.clearValidate('logoUrl')

  // 第二种写法：nextTick()
  // 点击新增 响应式数据发生变化 模板进行二次更新，nextTick()里面去获取更新后的dom，
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}
// 修改品牌
const updateTrademark = (row:TradeMark)=> {
  // 清空检验规则错误提示信息
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
  // es6合并对象
  Object.assign(trademarkParams,row)
  dialogFormVisible.value = true
}
// 对话框取消
const cancel = ()=> {
  dialogFormVisible.value = false
}
// 对话框确认
const confirm = async()=> {
  // 调用这个方法进行全部表单校验，如果校验通过，再执行后面的语法
  await formRef.value.validate()
  let result:any = await reqAddOrUpdateTrademark(trademarkParams)
  if(result.code == 200){
    ElMessage.success(trademarkParams.id?'修改品牌成功':'添加品牌成功')
    dialogFormVisible.value = false
    getHasTrademark(trademarkParams.id?pageNo.value:1)
  }else{
    ElMessage.error(trademarkParams.id?'修改品牌失败':'添加品牌失败')
    dialogFormVisible.value = false
  }
}
// 图片上传成功之前触发的钩子函数，约束文件类型大小，rawFile当前上传文件对象，
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 上传文件格式：png|jpg|gif 4M
  if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
    if(rawFile.size/1024/1024 < 4){
      return true
    }else{
      ElMessage.error('上传文件大小应小于4M！')
      return false
    }
  } else{
    ElMessage.error('上传文件格式：png、jpg、gif！')
    return false
  }
}
// 图片上传成功的钩子函数 response:当前图片post请求 服务器返回的数据
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  trademarkParams.logoUrl = response.data //上传图片地址
  // 图片上传成功，清除掉对应图片校验结果
  formRef.value.clearValidate('logoUrl')
}
const validatorTmname = (rule:any,value:any,callback:any) => {
  if(value.trim().length >= 2){
    callback()
  }else{
    callback(new Error('品牌名称大于等于2位'))
  }
}
const validatorLogoUrl = (rule:any,value:any,callback:any) => {
  if(value){ //此处value是图片上传成功后返回的地址
    callback()
  }else{
    callback(new Error('请上传图片'))
  }
}
// 表单校验规则对象
const rules = {
  tmName:[{required: true,trigger: 'blur',validator:validatorTmname}],
  logoUrl:[{required: true,validator:validatorLogoUrl}],
}
// 气泡确认框删除回调
const removeTradeMark = async(id:number)=> {
  let result = await reqDeleteTrademark(id)
  if(result.code == 200){
    ElMessage.success('删除品牌成功')
    // 当前页数据全部删除 回到上一页
    getHasTrademark(trademarkArr.value.length>1?pageNo.value:pageNo.value-1)
  }else{
    ElMessage.error('删除品牌失败')
  }
}
</script>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>